package com.example.app.controller;

import com.example.app.config.JwtUtils;
import com.example.app.dto.*;
import com.example.app.entity.User;
import com.example.app.exception.InvalidPasswordException;
import com.example.app.exception.UserAlreadyExistsException;
import com.example.app.exception.UserNotFoundException;
import com.example.app.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final JwtUtils jwtUtils;

    @Autowired
    public UserController(UserService userService, JwtUtils jwtUtils) {
        this.userService = userService;
        this.jwtUtils = jwtUtils;
    }

    @PostMapping("/register")
    public ResponseEntity<?> register(@Valid @RequestBody RegisterRequest request) {
        try {
            userService.registerUser(request);
            return ResponseEntity.ok("注册成功");
        } catch (UserAlreadyExistsException e) {
            return ResponseEntity.status(HttpStatus.CONFLICT).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(@Valid @RequestBody LoginRequest request) {
        try {
            // 1. 验证用户凭据
            User user = userService.authenticateUser(request);

            // 2. 创建UserDetails对象
            UserDetails userDetails = new org.springframework.security.core.userdetails.User(
                    user.getUserId().toString(), // 使用userId作为用户名
                    user.getPassword(), // 加密后的密码
                    new ArrayList<>()
            );

            // 3. 生成JWT令牌
            String token = jwtUtils.generateToken(userDetails);

            // 4. 创建响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + token);
            headers.add("X-User-ID", user.getUserId().toString());

            // 5. 创建响应体
            Map<String, Object> response = new HashMap<>();
            response.put("message", "登录成功");
            response.put("token", token);
            response.put("userId", user.getUserId());

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(response);
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @DeleteMapping("/{userId}/delete")
    public ResponseEntity<?> deleteUser(@PathVariable Long userId) {
        try {
            userService.deleteUser(userId);
            return ResponseEntity.ok("用户删除成功");
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @PutMapping("/{userId}/password")
    public ResponseEntity<?> updatePassword(
            @PathVariable Long userId,
            @Valid @RequestBody PasswordUpdateRequest request) {
        try {
            userService.updatePassword(userId, request);
            return ResponseEntity.ok("密码更新成功");
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (InvalidPasswordException e) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器内部错误");
        }
    }

    @PutMapping("/{userId}/name")
    public ResponseEntity<?> updateName(
            @PathVariable Long userId,
            @Valid @RequestBody NameUpdateRequest request) {
        try {
            userService.updateName(userId, request);
            return ResponseEntity.ok("姓名更新成功");
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @GetMapping("/profile")
    public ResponseEntity<?> getUserProfile(
            @RequestParam("userId") Long userId) {
        try {
            UserProfileDTO profile = userService.getUserProfile(userId);
            return ResponseEntity.ok(profile);
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }

    @PostMapping("/profile")
    public ResponseEntity<?> updateUserProfile(
            @RequestParam("userId") Long userId,
            @Valid @RequestBody UserProfileDTO request) {
        try {
            UserProfileDTO updatedProfile = userService.updateUserProfile(userId, request);
            return ResponseEntity.ok(updatedProfile);
        } catch (UserNotFoundException e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(e.getMessage());
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.internalServerError().body("服务器错误");
        }
    }
}